IHG.ImageBrowser = function(options)
{
	if(typeof options.callback != 'function') {
		throw "Missing option: [callback] was not defined";
	}
	
	this.backendURI = IHG.Preferences.get('ImageBrowser.backendURI');
	if(!this.backend) {
		this.backend = prompt('Backend URI');
		IHG.Preferences.set('ImageBrowser.backendURI', this.backendURI);
	}
	
	this.container = document.createElement('div');
	this.container.className = 'IHGImageBrowser';
	
	this._loadingNode = document.createElement('div');
	this._loadingNode.appendChild(document.createTextNode('laden...'));
	
	this.callback = options.callback;
	
	this._isOpen = false;
	this._files = new Array();
}

IHG.ImageBrowser.prototype = {
	open: function()
	{
		if(!this._isOpen) {
			this._isOpen = true;
			this.container.display = 'block';
			this._openBrowser();
		} else {
			this.close();
		}
	},
	
	close: function()
	{
		this._isOpen = false;
		this.container.display = 'none';
	},
	
	_setContentNode: function(node)
	{
		if(this.container.firstChild) {
			this.container.removeChildNode(this.container.firstChild);
		}

		this.container.appendChild(node);
	},
	
	_openBrowser: function()
	{
		if(this._files.length === 0) {
			this._refresh();
			return;
		}
		
		var _self = this;
		
		var container = document.createElement('ul');
		for(var i = 0; i < this._files.length; i++) {
			var file = this._files[i];
			
			var listNode = document.createElement('li');
			var insertBtn = document.createElement('a');
				insertBtn.className = 'insertBtn';
				insertBtn.title = file.name + ' invoegen';
				//insertBtn.appendChild(document.createTextNode('Invoegen'));
			var deleteBtn = document.createElement('a');
				deleteBtn.className = 'deleteBtn';
				deleteBtn.title = file.name + ' verwijderen';
				deleteBtn.appendChild(document.createTextNode('Verwijderen'));
			var thumbnail = document.createElement('img');
				thumbnail.src = file.thumbnail;
			
			$(insertBtn).on('click', function() {
				_self.insertImage(file.url);
				return false;
			});
				
			$(deleteBtn).on('click', function() {
				_self.deleteImage(file.id);
				return false;
			});
			
			insertBtn.appendChild(thumbnail);
			listNode.appendChild(insertBtn);
			listNode.appendChild(deleteBtn);
			container.appendChild(listNode);
		}
		
		this._setContentNode(container);
	},
		
	_refresh: function()
	{
		this._setContentNode(this._loadingNode);
		
		var _self = this;
		var requestURI = this.backendURI + (this.backendURI.indexOf('?') === -1 ? '?' : '&') + 'method=listFiles';
		IHG.JSONRequest(requestURI, function(files) {
			_self._files = files;
			_self._openBrowser();
		}
	}
}